package com.kll.tv.views

import android.Manifest
import android.annotation.SuppressLint
import android.app.admin.DevicePolicyManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Handler
import android.view.View
import android.widget.Toast
import com.hihonor.android.app.admin.DeviceControlManager
import com.kll.carolinehmibiz.OperationManager
import com.kll.carolinehmibiz.model.AccountModel
import com.kll.carolinehmibiz.presentation.listener.WellcomeProtocol
import com.kll.carolinehmibiz.presentation.presenter.WellcomePresenter
import com.kll.tv.SampleDeviceReceiver
import com.kll.tv.base.views.BaseActivity
import com.kll.tv.databinding.ActivityWellcomeBinding
import com.kll.carolinehmibiz.base.utils.L
import kotlin.reflect.full.functions


class WellcomeActivity : BaseActivity<WellcomePresenter>(), WellcomeProtocol.IView {
    private lateinit var binding: ActivityWellcomeBinding
    private var handler = Handler()


    override fun initViewBinding(): View {
        binding = ActivityWellcomeBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createPresenter(): WellcomePresenter {
        return WellcomePresenter(this, this)
    }

    override fun init() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
          //  getSnWithDeviceOwner()
        }
        if (OperationManager.getInstancce().isLogin()) {
            startActivity(Intent(this, MainActivity::class.java))
            finish()
        } else {
            mPresenter.getDeviceStatus()
        }

    }

    override fun getDeviceStatusSuccessed(state: Int) {
        handler.postDelayed({
            if (state == 1) {
                gotoLoginActivity()
            } else {
                gotoActiveActivity()
            }
        }, 3000)
    }

    override fun getDeviceStatusFailed(message: String) {
        gotoActiveActivity()
    }


    private fun gotoActiveActivity() {
        startActivity(Intent(this, ActiveActivity::class.java))
        finish()
    }


    private fun gotoLoginActivity() {
        startActivity(Intent(this, LoginActivity::class.java))
        finish()
    }

    //update by rxwu 新增获取设备sn码
    var devicePolicyManager: DevicePolicyManager? = null;

    @SuppressLint("MissingPermission")
    private fun getSnWithDeviceOwner() {
        var mAdminName  = ComponentName(this,SampleDeviceReceiver::class.java)
        devicePolicyManager =
            getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager;
        if (!testIsActive()) {
            // activeLaunched=true;
            launchDeviceActive();
        } else {
            try {
                var controlManager = DeviceControlManager();
                var result = false;
                L.e("------getSnWithDeviceOwner---","设备已经激活")
                if (!controlManager.isForcedActiveDeviceAdmin(mAdminName)) {
                    result = controlManager.setForcedActiveDeviceAdmin(mAdminName, this)
                }
                result = controlManager.isForcedActiveDeviceAdmin(mAdminName);
                L.e("------getSnWithDeviceOwner---","result结果为：${result}");
                if (result) {
                    if (!devicePolicyManager!!.isDeviceOwnerApp(packageName)) {
                        var clz = DeviceControlManager::class
                         clz.functions.forEach {
                            if ("setDeviceOwnerApp".equals(it.name)) {
                                it.call(controlManager, mAdminName, packageName);
                            }
                        }
                    }
                }
                if (devicePolicyManager!!.isDeviceOwnerApp(packageName)) {
                    devicePolicyManager!!.setPermissionGrantState(
                        mAdminName,
                        mAdminName.packageName,
                        Manifest.permission.READ_PHONE_STATE,
                        DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
                    )
                    devicePolicyManager!!.setPermissionPolicy(
                        mAdminName,
                        DevicePolicyManager.PERMISSION_POLICY_AUTO_GRANT
                    )
                    requestPermissions(
                        arrayOf(Manifest.permission.READ_PHONE_STATE),
                        PackageManager.PERMISSION_GRANTED
                    )
                    //设置为全局设备编码
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        AccountModel.SN = Build.getSerial()
                    }
                    L.e("-----SN-----", "当前设备号是：" + AccountModel.SN)
                }
            } catch (e: Exception) {
                L.e("-----SN-----", e.message!!)
            }
        }
    }

    private fun testIsActive(): Boolean {
        var mAdminName  = ComponentName(this,SampleDeviceReceiver::class.java)
        var systemService = getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager;
        var ret = systemService.isAdminActive(mAdminName)

        if (ret) {
            Toast.makeText(this, "已激活为设备管理器", Toast.LENGTH_LONG).show();
        }
        return ret;
    }

    //拉起激活页面，手动激活
    companion object {
        const val SETTINGS_PACKAGE_NANE = "com.hihonor.homevision.settings";
        const val SETTING_CLASS_NMANE =
            "com.hihonor.homevision.settings.general.devicemanager.DeviceAdminAddActivity";

    }

    var activeLaunched = false;
    private fun launchDeviceActive() {
        var intent = Intent();
        intent.setClassName(SETTINGS_PACKAGE_NANE, SETTING_CLASS_NMANE);
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, ComponentName(this,SampleDeviceReceiver::class.java));
        startActivity(intent);
        activeLaunched = true;
    }
}